/*globals $jq, jQuery, CSPhotoSelector */

$jq(document).ready(function () {
    var selector, logActivity, callbackAlbumSelected, callbackPhotoUnselected, callbackSubmit;
    var buttonOK = $jq('#CSPhotoSelector_buttonOK');
    var totalSelectedToImport = 0;
    var totalFinishedImporting = 0;
    var totalSelectedToImportArray = new Array();
    var totalSelectedToImportResults = new Array();
    var o = this;


    /* --------------------------------------------------------------------
    * Photo selector functions
    * ----------------------------------------------------------------- */

    fbphotoSelect = function (id) {
        // if no user/friend id is sent, default to current user
        if (!id) id = 'me';

        callbackAlbumSelected = function (albumId) {
            var album, name;
            album = CSPhotoSelector.getAlbumById(albumId);
            // show album photos
            selector.showPhotoSelector(null, album.id);
        };

        callbackAlbumUnselected = function (albumId) {
            var album, name;
            album = CSPhotoSelector.getAlbumById(albumId);
        };

        callbackPhotoSelected = function (photoId) {
            var photo;
            photo = CSPhotoSelector.getPhotoById(photoId);
            buttonOK.show();
            //logActivity('Selected ID: ' + photo.id);
        };

        callbackPhotoUnselected = function (photoId) {
            var photo;
            album = CSPhotoSelector.getPhotoById(photoId);
            //buttonOK.hide();
        };

        callbackSubmit = function (photoArray) {
            totalSelectedToImport = photoArray.length;

            for (var i = 0; i < totalSelectedToImport; i++) {
                var photo;
                photo = CSPhotoSelector.getPhotoById(photoArray[i]);
                if (photo != null && photo.source != null) {
                    totalSelectedToImportArray.push(photo.source);
                } else {
                    totalSelectedToImport--;
                }
            }
            
            $jq('#FBImportTotalPhotosCount').text(totalSelectedToImport);
            UploadRemainingFacebookPhotos();
        };

        ForceLastUpload = function () {
            totalSelectedToImport = 0;
            totalSelectedToImportArray.splice(0, totalSelectedToImportArray.length);
            setTimeout(AutoRedirectWhenCanceled, 3000);
        };

        AutoRedirectWhenCanceled = function (redirectUrl) {
            location.href = FRONT_SITE_URL+'user/profile/MediaUpload?errorcode=124&allResults=' + totalSelectedToImportResults;
        };

        UploadRemainingFacebookPhotos = function (redirectUrl) {
            //redirectUrl = 5;
            if ((totalSelectedToImport == 0 || totalSelectedToImportArray.length == 0) && redirectUrl == null) {
                AutoRedirectWhenCanceled();
            }

            if (totalSelectedToImportArray.length > 0) {
                $jq('#FBImportCurrentPhotoCount').text(totalFinishedImporting + 1);
                UploadSelectedFacebookPhoto(totalSelectedToImportArray[0]);
                totalSelectedToImportArray.splice(0, 1);
            }

            if (totalFinishedImporting >= totalSelectedToImport && redirectUrl != null) {
                location.href = 'MediaUpload/?'+redirectUrl + "&allResults=" + totalSelectedToImportResults;
                //logActivity('<br><strong>DONE Importing</strong>');
            }
        };

        UploadSelectedFacebookPhoto = function (imgurl) {
            //logActivity('<br><strong>Importing</strong>: ' + imgurl + '<br>');
            $jq.ajax({
                type: 'POST',
                cache: false,
                data: {photourl:imgurl},
                //url: FRONT_SITE_URL+"user/profile/grabfacebookphoto?photourl=" + imgurl,
                url: FRONT_SITE_URL+"user/profile/grabfacebookphoto",
                success: function (result) {
                    totalFinishedImporting++;
                    totalSelectedToImportResults.push(result.message);
                    var results = $.parseJSON(result);
                    UploadRemainingFacebookPhotos(results['redirect']);
                }
            });
        };

        // Initialise the Photo Selector with options that will apply to all instances
        CSPhotoSelector.init({ debug: false });

        // Create Photo Selector instances
        selector = CSPhotoSelector.newInstance({
            callbackAlbumSelected: callbackAlbumSelected,
            callbackAlbumUnselected: callbackAlbumUnselected,
            callbackPhotoSelected: callbackPhotoSelected,
            callbackPhotoUnselected: callbackPhotoUnselected,
            callbackSubmit: callbackSubmit,
            maxSelection: 30,
            albumsPerPage: 6,
            photosPerPage: 200,
            autoDeselection: true
        });

        // reset and show album selector
        selector.reset();
        selector.showAlbumSelector(id);
    };


    /* --------------------------------------------------------------------
    * Click events
    * ----------------------------------------------------------------- */

    loggedintofb = false;

    $jq(".CSPhotoSelector_Cancel").click(function () {
        $jq(this).text('canceling import...');
        ForceLastUpload();
    });

    $jq("#facebookPhotoSelect").click(function (e) {
        e.preventDefault();
        if (!loggedintofb) {
            FB.login(function (response) {
                if (response.authResponse) {
                    loggedintofb = true;
                    loadfbphotoAlbum();
                }
            }, { scope: 'user_photos, friends_photos' });
        }
        else {
            loadfbphotoAlbum();
        }
    });

    loadfbphotoAlbum = function () {
        id = null;
        if ($jq(this).attr('data-id')) id = $jq(this).attr('data-id');
        fbphotoSelect(id);
    };

    logActivity = function (message) {
        //$jq("#testresults").append('<div>' + message + '</div>');
    };
});